// 请求麦克风权限
export async function requestMicrophone() {
  try {
    const constraints = {
      audio: {
        echoCancellation: true,
        noiseSuppression: true,
        sampleRate: 48000
      },
      video: false
    };
    
    const stream = await navigator.mediaDevices.getUserMedia(constraints);
    return stream;
  } catch (error) {
    console.error('请求麦克风失败:', error);
    throw error;
  }
}

// 请求摄像头权限
export async function requestCamera() {
  try {
    const constraints = {
      video: {
        width: { ideal: 1280 },
        height: { ideal: 720 },
        frameRate: { ideal: 30 }
      },
      audio: false
    };
    
    const stream = await navigator.mediaDevices.getUserMedia(constraints);
    return stream;
  } catch (error) {
    console.error('请求摄像头失败:', error);
    throw error;
  }
}

// 请求屏幕共享
export async function requestScreenSharing() {
  try {
    const constraints = {
      video: {
        cursor: 'always'
      },
      audio: {
        echoCancellation: true,
        noiseSuppression: true
      }
    };
    
    const stream = await navigator.mediaDevices.getDisplayMedia(constraints);
    
    // 添加停止事件监听
    const videoTrack = stream.getVideoTracks()[0];
    if (videoTrack) {
      videoTrack.onended = () => {
        console.log('屏幕共享已停止');
      };
    }
    
    return stream;
  } catch (error) {
    console.error('请求屏幕共享失败:', error);
    throw error;
  }
}

// 释放媒体资源
export function releaseMediaResources(stream) {
  if (!stream) return;
  
  stream.getTracks().forEach(track => {
    try {
      track.stop();
    } catch (error) {
      console.warn('停止媒体轨道失败:', error);
    }
  });
}